package cn.hsa.fqz.handler;

import cn.hsa.fqz.common.annotation.SA;
import cn.hsa.fqz.common.consts.UserConstant;
import cn.hsa.fqz.common.exception.GolbalEorrcode;
import cn.hsa.fqz.task.service.dto.LoginUserDTO;
import cn.hsa.hsaf.core.framework.web.exception.AppException;

import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * LoginUser 参数解析
 */

public class LoginAnnotationArgumentResolver implements HandlerMethodArgumentResolver {

  @Override
  public boolean supportsParameter(MethodParameter methodParameter) {
    return methodParameter.getParameterType().isAssignableFrom(LoginUserDTO.class)
        && methodParameter.hasParameterAnnotation(SA.class);
  }

  @Override
  public Object resolveArgument(MethodParameter methodParameter,
                                ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) {
    HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
    if (Objects.nonNull(request)) {
      Object userInfo =  request.getAttribute(UserConstant.USER_INFO);
      if(Objects.isNull(userInfo)){
        throw new AppException(GolbalEorrcode.UN_AUTH.getCode(),GolbalEorrcode.UN_AUTH.getName());
      }
      return userInfo;
    }
    return null;
  }

}
